<template>
    <el-container>
        <el-header>Header</el-header>
        <el-main>
            <div class="container clearflx">
                <span>补单-{{ carNumber }}</span>
                <div class="btn">

                    <button class="btn1" @click="goBack">返回</button>
                </div>
            </div>
            <div class="content clearflx">
                <div class="upper">
                    <div>
                        订单状态:
                        <el-checkbox v-model="WholeCar">拼车</el-checkbox>
                        <el-checkbox v-model="carPackage">包车</el-checkbox>
                        <el-checkbox v-model="ship">货件</el-checkbox>
                        <span class="orderTime">订单时间:
                            <el-select v-model="value" placeholder="请选择时间" @change="optionChange">
                                <el-option v-for="item in options" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </span>
                        <div class="Gaode">
                            <MapContainer :driver_id="driverId"></MapContainer>
                            <div class="imgExample">
                                <!-- 每个div和span组合在一个flex容器中 -->
                                <div class="item">
                                    <div class="img1"></div>
                                    <span>司机起点</span>
                                </div>
                                <div class="item">
                                    <div class="img2"></div>
                                    <span>乘客（已接）</span>
                                </div>
                                <div class="item">
                                    <div class="img3"></div>
                                    <span>乘客（未接）</span>
                                </div>
                                <div class="item">
                                    <div class="img4"></div>
                                    <span>乘客（待补）</span>
                                </div>
                                <div class="item">
                                    <img src="../assets/图示司机位置.png" alt="">
                                    <span>司机位置</span>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>

                <div>
                    <button class="btn3" @click="sortValue(0)">推荐</button>
                    <button class="btn3" @click="sortValue(1)">距离优先</button>
                    <button class="btn3" @click="sortValue(2)">时间优先</button>

                    <button class="btn2" @click="query">查询</button>
                    <button class="btn4" @click="supplement">补单</button>
                </div>
                <div class="table1 clearflx">
                    <el-table :data="tableData1" @selection-change="handleSelectionChange" height="295">
                        <el-table-column type="selection" width="60px">

                        </el-table-column>
                        <el-table-column prop="order_type" label="订单类型" width="115px">
                            <template slot-scope="scope">
                                {{ orderType(scope.row.order_type) }}{{ scope.row.order_detail.count }}人[即]
                            </template>
                        </el-table-column>
                        <el-table-column prop="appoint_time" label="预约时间" :formatter="DateFormat" width="115px">
                        </el-table-column>
                        <el-table-column prop="order_detail.start.address" label="上车点" width="115px">
                        </el-table-column>
                        <el-table-column prop="order_detail.end.address" label="下车点" width="115px">

                        </el-table-column>
                        <el-table-column label="匹配系数">

                        </el-table-column>

                    </el-table>
                </div>
            </div>
            <div class="bottom">
                <p>实时线路数据</p>
                <el-table :data="tableData2" height="120">
                    <el-table-column label="编号" width="115px">
                        <template slot-scope="scope">
                            {{ getCode(scope.$index) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="order_type" label="订单类型" width="115px">
                        <template slot-scope="scope">
                            {{ orderType(scope.row.order_type) }}人工补单{{ scope.row.order_detail.count }}人[即]
                        </template>
                    </el-table-column>
                    <el-table-column prop="phone" label="手机号码" :formatter="phoneNumber" width="115px"></el-table-column>
                    <el-table-column prop="appoint_time" label="预约时间" :formatter="DateFormat" width="115px">

                    </el-table-column>
                    <el-table-column prop="order_detail.start.address" label="上车点" width="115px">

                    </el-table-column>
                    <el-table-column prop="order_detail.end.address" label="下车点" width="115px"></el-table-column>
                    <el-table-column label="预计接送时间" width="115px"></el-table-column>
                    <el-table-column prop="order_status" label="订单状态" width="115px">
                        <template slot-scope="scope">
                            <span :style="orderStatus(scope.row.pay_status).style">{{
                                orderStatus(scope.row.pay_status).text
                            }}</span>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            

        </el-main>
    </el-container>
</template>
<script>
import MapContainer from '@/components/MapContainer.vue';
import axios from 'axios';

export default {
    name: 'supplement',
    created() {
        this.carNumber = this.$route.query.car_number;
        this.lineId = this.$route.query.line_id;
        this.driverId = this.$route.query.driver_id;
        this.dispatchedId = this.$route.query.dispatched_id;
        this.connect();


    },
    components: {
        MapContainer
    },
    data() {
        return {
            WholeCar: '',
            carPackage: '',
            ship: '',
            carNumber: '',
            optionType: [],//存储用户在选择订单时间时选择的选项
            tableData1: [],//存储表格里面的数据
            tableData2: [],//存储下方表格数据
            selectedData: [],//存储被选中的数据
            sortTypeValue: 0,//默认用推荐方法进行排序
            startTime: '',//存储开始时间
            startPoint: [],//存储tableData2的上车点经纬度
            endPoint: [],//存储tableData2的下车点经纬度
            options: [{
                value: '选项1',
                label: '一小时内'
            }, {
                value: '选项2',
                label: '两小时内'
            }, {
                value: '选项3',
                label: '一天内'
            }, {
                value: '选项4',
                label: '两天内'
            }, {
                value: '选项5',
                label: '一个月内'
            }],
            value: '选项1'
        }
    },
    methods: {
        goBack() {
            this.$router.go(-1)
        },
        recommend() {
            console.log("按钮被点击了");
        },
        distance() {
            console.log("距离优先");
        },
        timeFirst() {
            this.tableData1.sort((a, b) => {
                const dateA = new Date(a.appoint_time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
                const dateB = new Date(b.appoint_time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
                return dateA.localeCompare(dateB)
            })
            //console.log("timeFirst 被调用");检测方法是否成功
        },
        formatDate(date) {
            const year = date.getFullYear();
            const month = (date.getMonth() + 1).toString().padStart(2, '0');
            const day = date.getDate().toString().padStart(2, '0');
            const hours = date.getHours().toString().padStart(2, '0');
            const minutes = date.getMinutes().toString().padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:00`;
        },
        optionChange() {
            let current = new Date()
            console.log(current);
            current.setSeconds(0)

            switch (this.value) {
                case '选项1':
                    current.setHours(current.getHours() - 1)
                    break;
                case '选项2':
                    current.setHours(current.getHours() - 2)
                    break;
                case '选项3':
                    current.setDate(current.getDate() - 1)
                    break;
                case '选项4':
                    current.setDate(current.getDate() - 2)

                    break;
                case '选项5':
                    current.setDate(current.getDate() - 30)
                    break;
                default:
            }
            this.startTime = this.formatDate(current)//格式化当前时间,并把它作为开始时间传入query方法中
            console.log(this.startTime);
        },
        query() {
            const selectedTypes = this.getSelectedOrderTypes();
            const endTime = this.formatDate(new Date())

            axios.post('/pub/ai/add_order_list', {
                driver_id: this.driverId,
                line_id: this.lineId,
                max_distance: 0,
                limit: 100,
                dispatched_id: this.dispatchedId,
                order_type: selectedTypes,
                start_appoint_time: this.startTime,
                end_appoint_time: endTime,
                sort_type: this.sortTypeValue,
                pos: 0,
                oc_code: ["10596"]
            }, {
                headers: {
                    "user-token": "12306070809_" + "6ac2ce7d291b4dffa9053edc6650ce9b",
                },
            })
                .then(response => {
                    this.tableData1 = response.data.result.list
                    console.log(response);
                    console.log(this.driverId);


                })
                .catch(err => {
                    console.error(err);
                })
        },
        supplement() {
            // 假设 this.selectedData 已经存储了被选中的行数据
            if (this.selectedData.length === 0) {
                alert('请至少选择一条数据进行补单！');
                return;
            }

            // 发送请求到服务器进行补单操作
            axios.post('/pub/ai/add_orders', {
                dispatched_id: this.dispatchedId,
                driver_id: this.driverId,
                line_id: this.lineId,
                order_ids: this.selectedData.map(item => item.order_id) // 使用选中数据的 order_id 数组
            }, {
                headers: {
                    "user-token": "12306070809_" + "6ac2ce7d291b4dffa9053edc6650ce9b",
                }
            })
                .then(response2 => {
                    // 补单成功后，将选中的订单数据添加到 tableData2 中
                    this.tableData2 = [...this.tableData2, ...this.selectedData];
                    this.selectedData = []; // 清空已选中的数据，避免重复添加
                    console.log(response2);
                })
                .catch(err => {
                    console.error(err);
                });
        },
        handleSelectionChange(selection) {
            this.selectedData = selection;
        },
        orderType(order_type) {
            switch (order_type) {
                case 0: return '拼车'
                case 1: return '包车'
                case 2: return '限时速递'
                case 3: return '市内用车'
                case 4: return '定制班线'
                case 5: return '多日包车'
                case 8: return '代驾订单'
                default: return "0";
            }

        },
        orderStatus(pay_status) {
            const color = pay_status === 0 ? '#2CBB82' : 'red';
            return {
                style: `color: ${color};`, // 返回内联样式
                text: pay_status === 0 ? '已完成' : '未完成' // 返回状态文本
            };
        },
        phoneNumber(row, column, phone) {

            const before = phone.substring(0, 3);
            const after = phone.substring(phone.length - 4);
            return `${before}****${after}`
        },
        connect() {
            axios.post('/pub/ai/get_dispatched_detail', {
                driver_id: this.driverId,
                line_id: this.lineId,
                dispatched_id: this.dispatchedId

            }, {
                headers: {
                    "user-token": "12306070809_" + "6ac2ce7d291b4dffa9053edc6650ce9b",
                },
            })
                .then(response1 => {
                    this.tableData2 = response1.data.result.list
                    //console.log(response1);
                    this.startPoint = [],
                        this.endPoint = [],
                        this.tableData2.forEach(item => {
                            this.startPoint.push({
                                lng: item.order_detail.start.location.lng,
                                lat: item.order_detail.start.location.lat
                            });
                            this.endPoint.push({
                                lng: item.order_detail.end.location.lng,
                                lat: item.order_detail.end.location.lat
                            });
                        });
                    console.log("起点数组：", this.startPoint);
                    console.log("终点数组：", this.endPoint);
                    this.$bus.$emit('test', this.startPoint, this.endPoint)


                })
                .catch(err => {
                    console.error(err);
                })
        },

        getSelectedOrderTypes() {
            let selectedTypes = [];
            if (this.WholeCar) {
                selectedTypes.push(0); // 拼车
            }
            if (this.carPackage) {
                selectedTypes.push(1); // 包车
            }
            if (this.ship) {
                selectedTypes.push(2); // 货件
            }
            return selectedTypes;

        },
        DateFormat(row, column, appoint_time) {
            const date = new Date(appoint_time);
            const hours = date.getHours().toString().padStart(2, '0');
            const minutes = date.getMinutes().toString().padStart(2, '0');
            return `${hours}:${minutes}`;
        },
        sortValue(sort_type) {
            this.sortTypeValue = sort_type; // 更新sort_type值
            this.sortType(this.sortTypeValue); // 调用sortType方法并传递当前的sort_type值
            this.query();//点击按钮时调用接口
        },

        sortType(sort_type) {
            // 根据sort_type调用不同的排序逻辑
            switch (sort_type) {
                case 0:
                    // 推荐排序
                    this.recommend();
                    break;
                case 1:
                    // 距离优先排序
                    this.distance();
                    break;
                case 2:
                    // 时间优先排序
                    this.timeFirst();
                    break;
                default:
                    console.error('Invalid sort type');
            }
            return (sort_type)
        },
        //根据ASCii码进行编号
        getCode(index) {
            const beginCode = 'A'.charCodeAt(0)
            return String.fromCharCode(beginCode + index)
        },


    },
}
</script>

<style scoped>
.container {
    height: 54px;
    position: relative;
    border: 1px solid #EBEEF5;
}

.btn {
    float: right;
}


.btn1 {
    width: 64px;
    height: 36px;
    border-radius: 4px;
    border: 1px solid #DCDFE6;
    margin-right: 16px;
}

.clearflx::after {
    /* clearflx 为清除浮动的样式 */
    content: '';
    display: block;
    clear: both;
}

.content {
    height: 763px;
}

.orderTime {
    margin-left: 30px;
}

.btn2,
.btn4 {
    width: 64px;
    height: 36px;
    border-radius: 4px;
    background: #1989FA;
    color: #FFFFFF;
    margin-left: 20px;
}

.btn3 {
    width: 68px;
    height: 36px;
    background: #E6F1FC;
    border-radius: 4px 0px 0px 4px;
    border: 1px solid #A3D0FD;
    margin-top: 42px;
    cursor: pointer;
}

.btn3:active {
    background-color: #1989FA;
}


.btn4 {
    margin-left: 221px;
}

.table1 {
    margin-top: 20px;
    width: 600px;
}

.Gaode {
    width: 656px;
    height: 420px;
    background: 1px solid black;
    border: 1px solid;
    float: right;
    margin-left: 40px;
    margin-top: 16px;
}

.imgExample {
    display: flex;
    margin-top: 16px;
}

.imgExample span {
    margin-left: 14px;
    padding-right: 30px;

}

.item {
    display: flex;
    align-items: center;
    margin: 0, 14px;
}

.img1,
.img2,
.img4,
.img3 {
    width: 8px;
    height: 8px;
    border-radius: 50%;
}

.img2 {
    background-color: #2CBB82;
    margin-left: 10px;
}

.img1 {
    background: #1989FA;
}

.img3 {
    background: #FF9845;
}

.img4 {
    background: #F56C6C;
}




p {
    margin-top: 40px;
}

.el-table {
    margin-top: 21px;
}
</style>